package com.rich.dao.impl;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.rich.constant.Constant;
import com.rich.dao.ProductDao;
import com.rich.domain.PageBean;
import com.rich.domain.Product;
import com.rich.domain.User;
import com.rich.utils.DataSourceUtils;

public class ProductDaoImpl implements ProductDao{

	QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
	/**
	 * 查询热门商品
	 */
	@Override
	public List<Product> findHot() throws Exception {
		String sql = "SELECT * FROM product WHERE is_hot = ? AND pflag = ? ORDER BY pdate DESC LIMIT 9";
		return qr.query(sql, new BeanListHandler<>(Product.class), Constant.PRODUCT_IS_HOST,Constant.PRODUCT_IS_UP);
	}

	/**
	 * 查询最新商品
	 */
	@Override
	public List<Product> findNew() throws Exception {
		String sql = "SELECT * FROM product WHERE pflag = ? ORDER BY pdate DESC LIMIT 9";
		return qr.query(sql, new BeanListHandler<>(Product.class), Constant.PRODUCT_IS_UP);
	}
	
	/**
	 *根据pid获取商品信息 
	 */
	@Override
	public Product getById(String pid) throws Exception {
		String sql = "SELECT * FROM product WHERE pid = ? LIMIT 1";
		return qr.query(sql, new BeanHandler<>(Product.class), pid);
	}

	/**
	 * 查询不同类的分页数据
	 */
	@Override
	public List<Product> findByPage(PageBean<Product> pb, String cid) throws Exception {
		String sql = "SELECT * FROM product WHERE cid=? AND pflag=? ORDER BY pdate DESC LIMIT ?,?";
		return qr.query(sql, new BeanListHandler<>(Product.class), cid,Constant.PRODUCT_IS_UP,pb.getStartIndex(),pb.getPageSize());
	}

	/**
	 * 查询不同类的总条数
	 */
	@Override
	public int getTotalRecord(String cid) throws Exception {
		String sql = "SELECT COUNT(*) FROM product WHERE cid=? AND pflag=?";
		//注意先转成new ScalarHandler()的long类型在转回int型
		return ((Long) qr.query(sql, new ScalarHandler(),cid,Constant.PRODUCT_IS_UP)).intValue();
	}

	/**
	 * 获取所有商品信息
	 */
	@Override
	public List<Product> findAll() throws Exception {
		String sql = "SELECT * FROM product WHERE pflag = ?";
		return qr.query(sql, new BeanListHandler<>(Product.class),Constant.PRODUCT_IS_UP);
	}

	/**
	 * 添加商品
	 */
	@Override
	public void save(Product p) throws Exception {
		String sql = "INSERT INTO product VALUES(?,?,?,?,?,?,?,?,?,?);";
		qr.update(sql,p.getPid(),p.getPname(),p.getMarket_price(),p.getShop_price(),p.getPimage(),
				p.getPdate(),p.getIs_hot(),p.getPdesc(),p.getPflag(),p.getCategory().getcID());
	}

}
